import 'dart:convert';

import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:oramemo/common/styles/colors.dart';
import 'package:oramemo/entity/custom_adjustemt_entity.dart';
import 'package:oramemo/entity/requst/device_put_entity.dart';
import 'package:oramemo/generated/assets.dart';
import 'package:oramemo/pages/facility/blue/custom_recode/custom_recode_view.dart';
import 'package:oramemo/widget/my_button.dart';
import 'custom_adjustment_logic.dart';
import 'custom_des_view.dart';
import 'widget/my_slider.dart';

class CustomAdjustmentPage extends StatelessWidget {
  const CustomAdjustmentPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final logic = Get.put(CustomAdjustmentLogic());

    return GetBuilder<CustomAdjustmentLogic>(builder: (logic) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('自定义调节'),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios),
            onPressed: () => Get.back(),
          ),
          actions: [
            if (!logic.isEdit.value)
              IconButton(
                icon: const Icon(
                  Icons.settings,
                  color: Colours.text_gray,
                ),
                onPressed: () {
                  logic.isEdit.value = true;
                  logic.update();
                },
              ),
            if (!logic.isEdit.value)
              Padding(
                padding: const EdgeInsets.only(right: 10.0),
                child: IconButton(
                  icon: const Icon(
                    AntdIcon.menu,
                    color: Colours.text_gray,
                  ),
                  onPressed: () async {
                    final DevicePutEntity res =
                        await Get.to(const CustomRecodePage());
                    if (res.deviceConfig?.isNotEmpty == true) {
                      logic.loadCustom(res.deviceConfig!);
                    }
                  },
                ),
              ),
            if (logic.isEdit.value)
              IconButton(
                icon: IconX.image(
                  Assets.facilityLeft,
                  size: 24,
                  color:
                      logic.canUndo.value ? Colours.text : Colours.text_gray_c,
                ),
                onPressed: () {
                  // 撤销操作
                  if (logic.canUndo.value) {
                    logic.undo();
                  }
                },
              ),
            if (logic.isEdit.value)
              IconButton(
                icon: IconX.image(
                  Assets.facilityRight,
                  size: 24,
                  color:
                      logic.canRedo.value ? Colours.text : Colours.text_gray_c,
                ),
                onPressed: () {
                  // 重做操作
                  if (logic.canRedo.value) {
                    logic.redo();
                  }
                },
              ),
          ],
        ),
        body: ListView(
          children: [
            // 左右耳切换按钮
            Padding(
              padding: EdgeInsets.fromLTRB(47.w, 50.h, 18.w, 18.h),
              child: Row(
                children: [
                  Expanded(
                    child: Obx(() => _buildEarButton(
                          title: '左耳',
                          isSelected: logic.isRightEar.value == false,
                          onTap: () => logic.selectEar(false),
                        )),
                  ),
                  SizedBox(width: 8.w),
                  Expanded(
                    child: Obx(() => _buildEarButton(
                          title: '右耳',
                          isSelected: logic.isRightEar.value == true,
                          onTap: () => logic.selectEar(true),
                        )),
                  ),
                ],
              ),
            ),

            // 提示信息
            Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                SizedBox(width: 50.w),
                Expanded(
                  child: Obx(() {
                    if (logic.showTip1.value) {
                      return Container(
                        padding: EdgeInsets.all(12.w),
                        decoration: BoxDecoration(
                          color: const Color(0xFFF9FBFF),
                          border: Border.all(color: Color(0xFF8AB4EB)),
                          borderRadius: BorderRadius.circular(16.r),
                        ),
                        child: Text(
                          '提示：\n滑动调整增益值（-12到+12），正值放大声音，负值降低音量，根据环境噪音或听力需求微调至清晰舒适。',
                          style: TextStyle(
                            fontSize: 10.sp,
                            color: Color(0xFF454655),
                          ),
                        ),
                      );
                    } else {
                      return SizedBox.shrink();
                    }
                  }),
                ),
                GestureDetector(
                  onTap: () {
                    logic.showTip1.value = !logic.showTip1.value;
                  },
                  child: Padding(
                    padding: EdgeInsets.only(top: 5.h, bottom: 5.0.h),
                    child: Icon(
                      Icons.info_outline,
                      color: Colours.text,
                      size: 25.sp,
                    ),
                  ),
                ),
                SizedBox(width: 30.w),
              ],
            ),

            SizedBox(height: 14.h),

            // 频率调节滑块
            Padding(
              padding: EdgeInsets.only(right: 16.w),
              child: Column(
                children: [
                  // 频率滑块组
                  Row(
                    children: [
                      // 频率调节标题
                      SizedBox(
                        width: 58.w,
                        height: 267.h,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            Padding(
                              padding: EdgeInsets.only(top: 0.h, bottom: 10.h),
                              child: Column(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                mainAxisSize: MainAxisSize.max,
                                children: [
                                  Text(
                                    '12',
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  Row(
                                    children: [
                                      Text(
                                        '增\n益\n(dB)',
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                          fontSize: 12.sp,
                                          color: Colours.text_gray,
                                        ),
                                      ),
                                      Text(
                                        '0',
                                        style: TextStyle(
                                          fontSize: 14.sp,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                    ],
                                  ),
                                  Text(
                                    '-12',
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            Padding(
                              padding: EdgeInsets.only(top: 0.h, bottom: 10.h),
                              child: Column(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                mainAxisSize: MainAxisSize.max,
                                children: [
                                  Text(
                                    '-',
                                    style: TextStyle(
                                        fontSize: 14.sp,
                                        fontWeight: FontWeight.bold,
                                        color: Colours.app_main),
                                  ),
                                  Text(
                                    '-',
                                    style: TextStyle(
                                        fontSize: 14.sp,
                                        fontWeight: FontWeight.bold,
                                        color: Colours.app_main),
                                  ),
                                  Text(
                                    '-',
                                    style: TextStyle(
                                        fontSize: 14.sp,
                                        fontWeight: FontWeight.bold,
                                        color: Colours.app_main),
                                  ),
                                ],
                              ),
                            ),
                            Container(
                              width: 1.w,
                              height: 261.h,
                              margin: EdgeInsets.only(
                                  left: 0.w, top: 8.h, right: 0.w, bottom: 0.h),
                              color: Color(0xFFD9D9D9),
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            _buildFrequencySlider(
                              logic,
                              logic.freq250,
                            ),
                            _buildFrequencySlider(
                              logic,
                              logic.freq500,
                            ),
                            _buildFrequencySlider(
                              logic,
                              logic.freq1k,
                            ),
                            _buildFrequencySlider(
                              logic,
                              logic.freq2k,
                            ),
                            _buildFrequencySlider(
                              logic,
                              logic.freq3k,
                            ),
                            _buildFrequencySlider(
                              logic,
                              logic.freq4k,
                            ),
                            _buildFrequencySlider(
                              logic,
                              logic.freq6k,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),

                  Container(
                    width: double.infinity,
                    height: 1.h,
                    margin:
                        EdgeInsets.only(left: 31.w, right: 15.w, bottom: 0.h),
                    color: Color(0xFFD9D9D9),
                  ),

                  // 频率标签
                  Padding(
                    padding: EdgeInsets.only(right: 10.0.w),
                    child: Center(
                      child: Row(
                        children: [
                          Container(
                            width: 1.h,
                            height: 20.h,
                            margin: EdgeInsets.only(
                                left: 57.w, right: 10.w, bottom: 2.h),
                            color: Color(0xFFD9D9D9),
                          ),
                          Expanded(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: [
                                _buildFrequencyLabel('250'),
                                _buildFrequencyLabel('500'),
                                _buildFrequencyLabel('1K'),
                                _buildFrequencyLabel('2K'),
                                _buildFrequencyLabel('3K'),
                                _buildFrequencyLabel('4K'),
                                _buildFrequencyLabel('6K'),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),

                  SizedBox(height: 4.h),

                  // 频率单位
                  Padding(
                    padding: EdgeInsets.only(left: 30.0.w),
                    child: Text(
                      '频率 (Hz)',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: Colours.text_gray,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 28.h),

            GestureDetector(
              onTap: () {
                logic.showTip2.value = !logic.showTip2.value;
                logic.update();
              },
              child: Padding(
                padding: EdgeInsets.only(left: 14.0.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Text(
                      '具体档位说明',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: Color(0xFF2573FF),
                        fontSize: 14,
                        fontFamily: 'Inter',
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                    SizedBox(
                      width: 0.w,
                    ),
                    IconX.image(
                      Assets.facilityMore,
                      width: 22.w,
                      height: 20.h,
                    ),
                  ],
                ),
              ),
            ),
            SizedBox(height: 15.h),
            if (logic.showTip2 == true) const CustomDesView(),
            SizedBox(height: 15.h),
            Padding(
              padding: EdgeInsets.only(left: 32.w, right: 18.w),
              child: DottedBorder(
                borderType: BorderType.RRect,
                radius: Radius.circular(20),
                color: Color(0xFF2573FF),
                dashPattern: [8, 4],
                strokeWidth: 1,
                child: Column(
                  children: [
                    SizedBox(height: 10.h),
                    Text(
                      '用户调节建议',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: const Color(0xFF2573FF),
                        fontSize: 14.sp,
                        fontFamily: 'Inter',
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 5.h),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          width: 17.w,
                        ),
                        Text(
                          '1.先定位问题频段:',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: const Color(0xFF303030),
                            fontSize: 12.sp,
                            fontFamily: 'Inter',
                            fontWeight: FontWeight.w700,
                          ),
                        ),
                        SizedBox(
                          width: 4.w,
                        ),
                        Expanded(
                          child: Text(
                            '听不清对话?优先调 1000-4000Hz.境太吵?先降 250-500Hz.',
                            style: TextStyle(
                              color: const Color(0xFF454655),
                              fontSize: 12.sp,
                              fontFamily: 'Inter',
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 12.w,
                        ),
                      ],
                    ),
                    SizedBox(height: 2.h),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          width: 17.w,
                        ),
                        Text(
                          '2.小步微调，实时试听:',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: const Color(0xFF303030),
                            fontSize: 12.sp,
                            fontFamily: 'Inter',
                            fontWeight: FontWeight.w700,
                          ),
                        ),
                        SizedBox(
                          width: 4.w,
                        ),
                        Expanded(
                          child: Text(
                            '每次调节幅度≤±3dB，戴好耳机试听对比效果',
                            style: TextStyle(
                              color: const Color(0xFF454655),
                              fontSize: 12.sp,
                              fontFamily: 'Inter',
                              fontWeight: FontWeight.w400,
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 12.w,
                        ),
                      ],
                    ),
                    SizedBox(height: 14.h),
                  ],
                ),
              ),
            ),
            // 保存按钮
            if (logic.isEdit.value)
              Padding(
                padding: EdgeInsets.fromLTRB(62.w, 30.h, 46.w, 30.h),
                child: Column(
                  children: [
                    MyButton(
                      radius: 12.r,
                      text: '保存',
                      onPressed: () {
                        // 保存设置
                        logic.saveSettings();
                      },
                    ),
                    SizedBox(height: 8.h),
                    Text(
                      '*使用当前参数并保存记录',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: Colors.black54,
                      ),
                    ),
                  ],
                ),
              ),
          ],
        ),
      );
    });
  }

  Widget _buildEarButton({
    required String title,
    required bool isSelected,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        height: 50.h,
        decoration: BoxDecoration(
          color: isSelected ? Colours.app_main : Colors.grey.shade300,
          borderRadius: BorderRadius.circular(25.r),
        ),
        child: Center(
          child: Text(
            title,
            style: TextStyle(
              fontSize: 20.sp,
              fontWeight: FontWeight.bold,
              color: isSelected ? Colors.white : Colors.black54,
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildFrequencySlider(CustomAdjustmentLogic logic, RxInt frequency) {
    return Padding(
      padding: EdgeInsets.only(top: 0.0.h, bottom: 14.h),
      child: SliderWidget(
        value: frequency,
        onChangeEnd: logic.isEdit.value == false
            ? null
            : (newValue) {
                logic.putFrequencyValue(frequency, newValue.round());
              },
        onChanged: logic.isEdit.value == false
            ? null
            : (newValue) {
                logic.setFrequencyValue(frequency, newValue.round());
              },
      ),
    );
  }

  Widget _buildFrequencyLabel(String label) {
    return SizedBox(
      width: 40.w,
      child: Text(
        label,
        textAlign: TextAlign.center,
        style: TextStyle(
            fontSize: 14.sp, color: Colors.black, fontWeight: FontWeight.bold),
      ),
    );
  }
}
